<template>
  <div>
    <q-card class="my-card" style="margin: 0 12px; padding: 0 50px">
      <div class="row items-center" style="width: 100%">
        <div style="width: 100%">
          <q-card-section class="col-sm-9 col-xs-8 q-px-none">
            <div
              class="row q-gutter-y-sm q-gutter-x-md justify-end"
              style="
                justify-content: space-between;
                width: 100%;
                align-items: center;
              "
            >
              <div class="bg-white q-pa-md">
                <div class="text-h6"><strong>部门设置</strong></div>
              </div>

              <div class="col-md-auto col-xs-12 q-pb-sm col-sm gt-sm">
                <q-btn
                  :ripple="false"
                  dense
                  flat
                  style="background: #1890ff; color: white; padding: 0 15px"
                  unelevated
                  icon="add"
                  class="no-border-radius q-px-sm"
                  label="添加部门"
                  @click="addTaskDialog"
                />
              </div>
            </div>
          </q-card-section>
        </div>
      </div>
    </q-card>
    <div class="q-px-sm q-mt-sm">
      <sc-page
        :items="DepartmentData"
        class="q-mt-sm"
        :datacounts="total"
        :perNumber="pageSize"
        @ChangeCurrentPage="getChangeCurrentPage"
        @ChangeInputPagePage="getChangeInputPagePage"
        item-class="col-xl-3 col-sm-4 col-xs-12"
      >
        <template v-slot:item="props">
          <q-intersection once>
            <sc-shadow>
              <q-card class="my-card" style="padding: 12px">
                <q-item-label
                  style="
                    font-size: 16px;
                    font-weight: bold;
                    padding: 10px 20px 20px;
                  "
                >
                  {{ props.item.company }}
                </q-item-label>
                <q-separator />
                <q-item>
                  <q-item-section avatar>
                    <q-avatar style="font-size: 80px">
                      <img :src="props.item.departimg" />
                    </q-avatar>
                  </q-item-section>
                  <q-item-section>
                    <q-item-label
                      class="text-body1 text-more"
                      v-if="userInfo.isadmin == 0"
                    >
                      <strong>{{ props.item.departname }}</strong>
                      <q-tooltip>{{ props.item.departname }}</q-tooltip>
                    </q-item-label>
                    <q-item-label
                      style="font-size: 25px"
                      class="text-body1 text-more"
                      v-else
                    >
                      <strong>{{ props.item.departname }}</strong>
                      <q-tooltip>{{ props.item.departname }}</q-tooltip>
                    </q-item-label>
                  </q-item-section>
                </q-item>
                <q-item class="q-px-sm" style="justify-content: flex-end">
                  <q-btn-group
                    flat
                    spread
                    class="full-width"
                    style="padding: 0; font-size: 10px; width: 100px !important"
                  >
                    <q-btn
                      flat
                      dense
                      icon="edit"
                      size="sm"
                      color="grey-6"
                      class="q-mx-sm"
                      @click="editItem(props.item)"
                    >
                      <q-tooltip>编辑</q-tooltip>
                    </q-btn>
                    <q-separator vertical inset="" />
                    <q-btn
                      flat
                      dense
                      icon="delete_forever"
                      size="sm"
                      color="red"
                      class="q-mx-sm"
                      @click="deleteItem(props.item)"
                    >
                      <q-tooltip>删除</q-tooltip>
                    </q-btn>
                  </q-btn-group>
                </q-item>
              </q-card>
            </sc-shadow>
          </q-intersection>
        </template>
      </sc-page>
    </div>
    <q-dialog
      v-model="addTask"
      fullscreen
      @escape-key="diahide"
      @hide="diahide"
      no-backdrop-dismiss
    >
      <q-card style="width: 60%; max-width: inherit" square class="q-pb-md">
        <q-card-section
          class="row items-center"
          style="background-color: #1890ff; color: #fff; padding-left: 40px"
        >
          <div class="text-h6">{{ task_title }}</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <form
          ref="addDataForm"
          @submit.prevent.stop="onSubmit"
          @reset.prevent.stop="onReset"
        >
          <q-card-section class="row justify-center">
            <div class="col-sm-12 col-xs-12 q-gutter-md">
              <!-- <q-input
                class="q-pb-none"
                ref="title"
                placeholder="请输入公司名称"
                outlined
                v-model="waitEdit.company"
                dense
                square
                clearable
                :rules="[
                  (val) => (val && val.length > 3) || '请输入公司名称并大于3个字符'
                ]"
              >
                <template v-slot:before>
                  <div class="text_name">公司名称</div>
                </template>
              </q-input> -->
              <q-input
                class="q-pb-none"
                placeholder="请输入部门"
                outlined
                v-model="waitEdit.departname"
                dense
                square
                clearable
              >
                <template v-slot:before>
                  <div class="text_name">部门</div>
                </template>
              </q-input>

              <div class="text_name">封面图</div>
              <div class="col-12 row flexRow">
                <el-upload
                  class="upload-demo"
                  :action="
                    upload_url +
                    '?guestcode=' +
                    waitEdit.guestcode +
                    '&imgpjid=' +
                    waitEdit.pjid
                  "
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :file-list="fileList"
                   list-type="picture-card"
                    :limit="9"
                >
                   <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog  :visible.sync="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </div>
              <div class="text-right">
                <q-btn
                  outline
                  unelevated
                  label="取消"
                  v-close-popup
                  type="reset"
                  class="q-mr-sm no-border-radius"
                  color="grey-6"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="发布"
                  color="primary"
                  class="no-border-radius"
                  v-if="isEdit == '0'"
                  :loading="loginLoading"
                />
                <q-btn
                  unelevated
                  type="submit"
                  label="保存"
                  color="primary"
                  class="no-border-radius"
                  :loading="loginLoading"
                  v-else
                />
              </div>
            </div>
          </q-card-section>
        </form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import ScShadow from 'components/shadow/ScShadow'
import ScPage from 'components/common/ScPage'
import { getLoginData } from '@/utils/localStorage'
import { getDepartmentApi, DepartmentApi, delimgApi } from '@/api/cardApi'
import { baseUrl, imgUrl, proUrl } from '@/utils/config'

export default {
  name: 'Department',
  components: { ScPage, ScShadow },
  data() {
    return {
      page: 1,
      pageSize: 20,
      total: 0,
      sort: '',
      userInfo: {},
      DepartmentData: [],
      addTask: false,
      waitEdit: {},
      loginLoading: false,
      isEdit: '',
      fileList: [],
      msg: '上传',
      upload_url: proUrl + '/api/InheartApi/uploadimg',
      imgfileList: [],
      qeditor: '',
      isdatatype: false,
      task_title: '添加',
      pjid: '',
      isdataicon: 'article',
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  methods: {
    getChangeCurrentPage(val) {
      this.getDepartmentData(val)
    },
    getChangeInputPagePage(val) {
      this.getDepartmentData(val)
    },
    getDepartmentData(pageindex) {
      let that = this
      let guestcode = that.userInfo.reguserno
      let gscode = that.userInfo.gscode
      let data = {}
      if (that.userInfo.isadmin == 1) {
        that.sort = 'a.id desc'
      }
      data = {
        guestcode: guestcode,
        gscode: gscode,
        pageindex: pageindex,
        pagesize: that.pageSize,
        sort: that.sort,
        keyword: that.keyword
      }
      getDepartmentApi(data).then((res) => {
        if (res.code == 0 && res.data.length > 0) {
          res.data.forEach((element) => {
            if (element.departimg != '') {
              element.departimg = imgUrl + element.departimg
            } else if (element.logoimg != '') {
              element.departimg = imgUrl + element.logoimg
            } else {
              element.departimg =
                'http://www.iqp168.com/src/assets/img/logo240x240.jpg'
            }
          })
          that.DepartmentData = res.data
          that.total = res.dataCount
        } else {
          that.DepartmentData = []
        }
      })
    },
    diahide() {
      let that = this
      that.getDepartmentData(1)
    },

    //上传
    handleRemove(file, fileList) {
      //console.log(file, fileList)
      let that = this
      let data_imgUrl = ''
      // let url = file.response.url + file.response.data
      let url = file.response.data
      const index = this.fileList.findIndex((item) => item.url === url)
      if (index !== -1) {
        this.fileList.splice(index, 1)
      }
      delimgApi({
        guestcode: that.waitEdit.guestcode,
        imgurl: url
      }).then((res) => {
        if (res.code == '0') {
          commonUtil.notifySuccess('删除成功')
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.$q.notify({
        color: 'white',
        textColor: 'positive',
        icon: 'check_circle',
        position: 'top',
        message: '上传成功'
      })
      let old = this.waitEdit.departimg
      if (this.waitEdit.departimg) {
        this.waitEdit.departimg = old + ',' + res.data
      } else {
        this.waitEdit.departimg = res.data
      }
      // console.log(res, file);
      // console.log(this.waitEdit.departimg);
    },
    changedata() {
      let that = this
      if (that.isdatatype) {
        that.isdataicon = 'video_library'
      } else {
        that.isdataicon = 'article'
      }
    },
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },
    //文本编辑器上传图片
    uploadIt() {
      this.EditorFileUpload()
    },
    EditorFileUpload() {
      document.getElementsByClassName('editorFile')[0].click()
    },
    AdvimgUpload() {
      document.getElementsByClassName('advFile')[0].click()
    },
    //添加按钮
    addTaskDialog() {
      this.fileList=[]
      // this.msg = '点击上传'
      // setTimeout(() => {
      //   const smallButton = document.getElementById('OldButton')
      //   const primaryButton = document.querySelector('#NewButton')
      //   smallButton.style.display = 'none'
      //   primaryButton.addEventListener('click', () => {
      //     smallButton.click()
      //   })
      // }, 500)
      this.isEdit = '0'
      this.waitEdit = {}
      this.addTask = true
      this.qeditor = ''
      this.task_title = '添加'
      this.imgfileList = []
      this.getCurrentTime()
      this.waitEdit.guestcode = this.userInfo.reguserno
      this.waitEdit.pjid = this.pjid
    },
    // 编辑
    editItem(item) {
      this.isEdit = '1'
      this.addTask = true
      // this.msg = '点击上传'
      // setTimeout(() => {
      //   const smallButton = document.getElementById('OldButton')
      //   const primaryButton = document.querySelector('#NewButton')
      //   smallButton.style.display = 'none'
      //   //console.log(primaryButton)
      //   primaryButton.addEventListener('click', () => {
      //     smallButton.click()
      //   })
      // }, 500)
      this.waitEdit = _.clone(item)
      this.qeditor = item.body
      this.task_title = '编辑部门'
      this.imgfileList = []
      if (
        this.waitEdit.departimg != '' &&
        this.waitEdit.departimg != undefined
      ) {
        for (var j = 0; j < this.waitEdit.departimg.split(',').length; j++) {
          this.imgfileList.push(this.waitEdit.departimg.split(',')[j])
        }
      }
      this.fileList = this.waitEdit.departimg.split(',').map((url, index) => ({
        name: `food${index + 1}.jpeg`,
        url: url
      }))
    },
    //删除
    deleteItem(item) {
      let that = this
      that.waitEdit = _.clone(item)
      const addModel = _.clone(that.waitEdit)
      addModel.guestcode = that.userInfo.reguserno
      addModel.gscode = that.userInfo.gscode
      addModel.sType = 'Delete'
      that.$q
        .dialog({
          title: '提示',
          message: '是否确认删除?',
          cancel: {
            'text-color': 'black',
            color: 'white',
            label: '取消'
          },
          ok: {
            label: '确定'
          },
          persistent: true
        })
        .onOk(() => {
          DepartmentApi(addModel).then((res) => {
            if ((res.code = '0')) {
              that.$q.notify({
                color: 'white',
                textColor: 'positive',
                icon: 'check_circle',
                position: 'top',
                message: '删除成功'
              })
              that.getDepartmentData(1)
            }
          })
        })
        .onCancel(() => {})
    },
    getCurrentTime() {
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      let ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      var code = ''
      var codeLength = 6
      var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
      for (var i = 0; i < codeLength; i++) {
        var index = Math.floor(Math.random() * 9)
        code += random[index]
      }
      this.pjid = yy + mm + dd + hh + mf + ss + code
    },
    onReset() {
      this.waitEdit.title = null
      this.waitEdit.name = null
      this.waitEdit.startTime = null
      this.waitEdit.desc = null
      this.waitEdit.id = null
      this.waitEdit.state = null
    },
    onSubmit() {
      let that = this
      that.loginLoading = true
      let addModel = {}
      if (that.isEdit == '0') {
        addModel.guestcode = that.userInfo.reguserno
        addModel.gscode = that.userInfo.gscode
        addModel.sType = 'Add'
        addModel.departname = that.waitEdit.departname ?? ''
        // addModel.company = that.waitEdit.company ?? ''
        addModel.departid = that.pjid
        addModel.departimg = that.waitEdit.departimg
        addModel.title = that.waitEdit.title
        addModel.body = that.qeditor
        addModel.isenable = true
        DepartmentApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '发布成功'
            })
            setTimeout(() => {
              that.getDepartmentData(1)
              that.loginLoading = false
              that.addTask = false
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      } else {
        addModel = _.clone(that.waitEdit)
        addModel.departimg = that.waitEdit.departimg.substring(6)
        addModel.departname = that.waitEdit.departname ?? ''
        // addModel.isenable = true
        // addModel.id = that.waitEdit.id
        addModel.sType = 'Edite'
        DepartmentApi(addModel).then((res) => {
          if (res.code == '0') {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: '修改成功'
            })
            setTimeout(() => {
              that.loginLoading = false
              that.addTask = false
              that.getDepartmentData(1)
            }, 1000)
          } else {
            that.$q.notify({
              color: 'white',
              textColor: 'positive',
              icon: 'check_circle',
              position: 'top',
              message: res.msg
            })
            that.loginLoading = false
          }
        })
      }
    }
  },
  mounted() {
    const user = getLoginData()
    if (user == null) {
      this.$router.push('/user/login')
      return
    }
    this.userInfo = user
    this.getDepartmentData(1)
  }
}
</script>

<style scoped>
#OldButton {
  display: none;
}
:deep(.el-upload-list__item-name) {
  display: none !important;
}
#NewButton {
  width: 200px;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  width: auto;
}
:deep(.el-upload-list) {
  display: flex;
  flex-wrap: wrap;
}
:deep(.el-upload-list--picture .el-upload-list__item-thumbnail) {
  width: 250px;
  height: 180px;
}
:deep(.el-upload-list--picture .el-upload-list__item) {
  margin-right: 10px;
  height: 200px;
  padding-right: 22px;
}
:deep(.el-upload-list) {
  display: flex;
  width: 100%;
}
.text-more {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  /*截取2行*/
  -webkit-box-orient: vertical;
  padding: 0 16px;
}
.text_name {
  width: 60px;
  text-align: left;
  color: #000;
  font-size: 14px;
}
</style>
